package com.example.project.model;


import com.example.project.base.BaseModel;
import com.example.project.net.ResultCallBack;
import com.example.project.util.LogUtil;
import com.example.project.util.ThreadManager;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.exceptions.HyphenateException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


//网络框架,Rxjava+Retrofit+okhttp
//okhttp:日志拦截器:4行; 缓存
//

public class MainModel extends BaseModel { public void getContacts(final ResultCallBack<Map<String, EaseUser>> callBack) {
    ThreadManager.getInstance()
            .execute(new Runnable() {
                @Override
                public void run() {
                    try {

                        //从服务器获取自己加入的和创建的群组列表，此api获取的群组sdk会自动保存到内存和db。
                        List<EMGroup> grouplist = EMClient.getInstance()
                                .groupManager()
                                .getJoinedGroupsFromServer();//需异步处理


                        //好友列表
                        List<String> usernames = EMClient.getInstance()
                                .contactManager()
                                .getAllContactsFromServer();

                        HashMap<String, EaseUser> map = new HashMap<>();
                        if (usernames != null && usernames.size() > 0) {

                            //好友
                            for (int i = 0; i < usernames.size(); i++) {
                                String name = usernames.get(i);
                                EaseUser value = new EaseUser(name);
                                value.setType(0);
                                map.put(name, value);
                            }
                        }

                        if (grouplist != null && grouplist.size() > 0) {
                            //群组
                            for (int i = 0; i < grouplist.size(); i++) {
                                EMGroup group = grouplist.get(i);
                                EaseUser value = new EaseUser(group.getGroupId());
                                value.setType(1);
                                map.put(group.getGroupId(), value);


                            }
                        }

                        callBack.onSuccess(map);
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        LogUtil.print(e.toString());
                        callBack.onFail(e.toString());
                    }
                }
            });
}
}
